<?php
/**
 * Created by PhpStorm.
 * User: peiyu
 * Date: 2019/7/8
 * Time: 10:40
 */

namespace app\index\controller;

use app\common\model\config;
use app\common\model\dictionary;
use app\common\model\dimension;
use think\facade\Request;


class Api
{
    protected $dimension = null;

    function __construct()
    {
        $this->dimension = dimension::getDimension();
    }

    public function selectConfig()
    {
        $params = Request::param();
        $needtotal = array_get($params, "needtotal", $page = array_get($params, "page", "1") === "1");
        $ret = [];
        if ($needtotal) {
            $ret["total"] = config::total($params);
        }
        $ret["list"] = config::selectConfig($params, $this->dimension);
        return json($ret);
    }

    public function distinctConfig()
    {
        $keys = $this->dimension;
        $keys["key"] = "key";
        $distinck = config::distinctConfig(array_keys($keys));
        return json(["keys" => $keys, "distinct" => $distinck]);

    }

    public function insertConfig()
    {
        config::insertConfig(Request::param(), $this->dimension,dimension::getDimensionList());

    }

    public function updateConfig()
    {
        config::updateConfig(Request::param(), $this->dimension);
    }


    public function delConfig()
    {
        config::delConfig(Request::param("id"));
    }

    public function getConfigValue()
    {
        if (!Request::param("key")) throw new \Exception("key is null");
        $obj = new \computeValue(array_keys($this->dimension), function ($item) {
            config::setLook($item);
        });
        $ret = $obj->get(Request::param("key"), Request::param(), function ($key) {
            return config::getConfigByKey($key);
        });

        $format=Request::param("_format","y");
        if($format=="n" || !$ret )return json($ret);

        $value_type=$ret["value_type"];
        $value=$ret["value"];
        switch ($value_type){
            case "string":
            case "code":
                return   json($value) ;
                break;
            case "int":
            case "float":
            case "json":
            case "array":
                return $value;
                break;
        }


    }

    public function getDictionary()
    {
        $tableData = dictionary::getTableData(Request::param("key"));
        //$tableData[]=["key"=>"","title"=>"","is_new"=>1];
        return json($tableData);
    }

    public function saveDictionary()
    {

        return dictionary::saveTableData(Request::param("key"), Request::post());
    }

    public function getDimension()
    {
        return json( dimension::getDimensionList());
    }

    public function saveDimension()
    {
        return dimension::saveDimension(Request::post());
    }
}